<template>
  <div class="city-weather">
    <div class="city">
      <span class="city-name">{{ cityName }}</span>
      <i class="iconfont icon-sanjiaoxia"></i>
    </div>

    <div class="weather">
      <span>{{ cityWeather }}</span
      ><br />
      <span>{{ tem }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, watch } from 'vue'
const map = inject('map')
const AMap = inject('AMap')

let cityName = ref('')
let cityWeather = ref('')
let tem = ref('')

watch(
  map,
  (newVal) => {
    if (newVal) {
      getweather()
    }
  },
  { immediate: true },
)

const getweather = () => {
  const citySearch = new AMap.value.CitySearch()
  citySearch.getLocalCity(function (status, result) {
    if (status === 'complete' && result.info === 'OK') {
      // 查询成功，result即为当前所在城市信息
      // console.log(result)
      // console.log(result.adcode)
      const weather = new AMap.value.Weather()
      cityName.value = result.city
      weather.getForecast(result.city, function (err, data) {
        // console.log(data)
        cityWeather.value = data.forecasts[0].dayWeather
        tem.value = `${data.forecasts[0].nightTemp}/${data.forecasts[0].dayTemp}℃`
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.city-weather {
  position: fixed;
  top: 10px;
  left: 400px;
  /* width: 360px; */
  height: 45px;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.15);
  background: #fff;
  border-radius: 3px;
  display: flex;
  align-items: center;
  padding: 10px;
  .city-name {
    font-weight: bolder;
  }
  .city:hover {
    cursor: pointer;
    .city-name,
    i {
      color: #0091ff;
    }
  }
  span,
  i {
    color: #555;
    font-size: 12px;
    margin: 0 3px;
  }
  .weather {
    text-align: center;
    margin-left: 5px;
  }
}
</style>
